import React, { useEffect, useState } from "react";

import styled from "styled-components";
import eventBus from "@/utils/eventBus";

import { ColorPicker } from "antd";
import type { ColorPickerProps, GetProp } from "antd";
import { message } from "antd";
import App from "@/script/App";
import { modelGroup, collisionModel, initialize } from "./config";
import CollideControls from "@/script/CollideControls";

const ScenePage = styled.div`
  width: 100vw;
  height: 100vh;
`;

let app: App;

function Collision() {
  let lastRaf: any = -1;
  const refThree = React.useRef<HTMLDivElement>(null!);

  useEffect(() => {
    app = new App(refThree.current);
    app.addLight();
    app.addAxesHelper(5);
    app.camera.position.set(-3, 3, 0.23);
    app.scene.add(modelGroup);
    app.orbitControls.enabled = false;
    const controls = new CollideControls(app.camera, app.renderer.domElement);
    controls.showAirWalls();

    initialize();

    //TODO：烘焙完八叉树为什么老是掉下去？
    setTimeout(() => {
      if (collisionModel) {
        controls.bake(collisionModel);
      }
    }, 1000);

    function animate() {
      lastRaf = requestAnimationFrame(animate);
      app.renderer.render(app.scene, app.camera);
      controls.update();
    }

    function onWindowResize() {
      app.camera.aspect = window.innerWidth / window.innerHeight;
      app.camera.updateProjectionMatrix();
      app.renderer.setSize(window.innerWidth, window.innerHeight);
    }

    window.addEventListener("resize", onWindowResize);

    animate();

    return () => {
      cancelAnimationFrame(lastRaf); // 清理渲染动画
      window.removeEventListener("resize", onWindowResize);
      app.renderer.dispose();
    };
  }, []);

  return (
    <div>
      <ScenePage ref={refThree}></ScenePage>
    </div>
  );
}

export default Collision;
